package com.kobeliu.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kobeliu.api.mq.DelayIndustryConfig;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.mapper.IndustryMapper;
import com.kobeliu.pojo.Industry;
import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.result.ResponseStatusEnum;
import com.kobeliu.service.IndustryService;
import com.kobeliu.utils.LocalDateUtils;
import com.tencentcloudapi.cvm.v20170312.models.CreateDisasterRecoverGroupRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@RequestMapping("industry")
@Slf4j
public class IndustryController extends BaseInfoProperties {

    @Autowired
    private IndustryService industryService;

    private static final String TOP_INDUSTRY_LIST = "top_industry_list";
    private static final String CHILD_INDUSTRY_LIST = "child_industry_list";

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostMapping("createNode")
    public GraceJSONResult createNode(@RequestBody Industry industry){
        if(!industryService.getIndustryIsExistByName(industry.getName())){
            return GraceJSONResult.errorMsg("该行业已经存在，请重新输入");
        }

        //节点创建
        industryService.createIndustry(industry);
        return GraceJSONResult.ok();
    }

    @GetMapping("getTopList")
    public GraceJSONResult getTopList(){

        long start = System.currentTimeMillis();

        //首先先去redis中去查，没有再去db
        String topIndustryListStr = redis.get(TOP_INDUSTRY_LIST);
        List<Industry> topIndustryList = null;
        if (StringUtils.isNotBlank(topIndustryListStr)) {
            topIndustryList = new Gson().fromJson(topIndustryListStr, new TypeToken<List<Industry>>() {}.getType());
        }else{
            topIndustryList = industryService.getTopIndustryList();
            //存入redis
            redis.set(TOP_INDUSTRY_LIST,new Gson().toJson(topIndustryList));
        }

        long sum = System.currentTimeMillis() - start;
        log.info("Industry-消耗的时间为：{}",sum);

        return GraceJSONResult.ok(topIndustryList);
    }

    @GetMapping("getChildList/{fatherId}")
    public GraceJSONResult getChildList(@PathVariable("fatherId")String fatherId){

        //首先先去redis中去查，没有再去db
        String topIndustryListStr = redis.get(CHILD_INDUSTRY_LIST+":byId="+fatherId);
        List<Industry> childIndustryList = null;
        if (StringUtils.isNotBlank(topIndustryListStr)) {
            childIndustryList = new Gson().fromJson(topIndustryListStr, new TypeToken<List<Industry>>() {}.getType());
        }else{
            childIndustryList = industryService.getChildIndustryList(fatherId);
            //存入redis
            redis.set(CHILD_INDUSTRY_LIST+":byId="+fatherId,new Gson().toJson(childIndustryList));
        }


        return GraceJSONResult.ok(childIndustryList);
    }

    //============================ APP使用 START ==============================
    @GetMapping("app/initTopList")
    public GraceJSONResult appInitTopList(){

        long start = System.currentTimeMillis();
        //首先先去redis中去查，没有再去db
        String topIndustryListStr = redis.get(TOP_INDUSTRY_LIST);
        List<Industry> topIndustryList = null;
        if (StringUtils.isNotBlank(topIndustryListStr)) {
            topIndustryList = new Gson().fromJson(topIndustryListStr, new TypeToken<List<Industry>>() {}.getType());
        }else{
            topIndustryList = industryService.getTopIndustryList();
            //存入redis
            redis.set(TOP_INDUSTRY_LIST,new Gson().toJson(topIndustryList));
        }

        long sum = System.currentTimeMillis() - start;
        log.info("Industry-消耗的时间为：{}",sum);

        return GraceJSONResult.ok(topIndustryList);
    }

    @GetMapping("app/getThirdListByTop/{fatherId}")
    public GraceJSONResult getThirdListByTop(@PathVariable("fatherId")String fatherId){

        //首先先去redis中去查，没有再去db
        String topIndustryListStr = redis.get(CHILD_INDUSTRY_LIST+":byId="+fatherId);
        List<Industry> childIndustryList = null;
        if (StringUtils.isNotBlank(topIndustryListStr)) {
            childIndustryList = new Gson().fromJson(topIndustryListStr, new TypeToken<List<Industry>>() {}.getType());
        }else{
            childIndustryList = industryService.getChildIndustryList(fatherId);
            //存入redis
            redis.set(CHILD_INDUSTRY_LIST+":byId="+fatherId,new Gson().toJson(childIndustryList));
        }


        return GraceJSONResult.ok(childIndustryList);
    }

    //============================ APP使用 END ================================

    @PostMapping("updateNode")
    public GraceJSONResult updateNode(@RequestBody Industry industry){
        //节点更新
        industryService.updateNode(industry);
        return GraceJSONResult.ok();
    }

    @PostMapping("deleteNode/{nodeName}")
    public GraceJSONResult deleteNode(@PathVariable("nodeName")String nodeName){
        //节点更新
        industryService.deleteNode(nodeName);
        return GraceJSONResult.ok();
    }

    private void resetRedisIndustry(Industry industry){
        if(industry.getLevel() == 1){
            //一级节点需要删除topList
            redis.del(TOP_INDUSTRY_LIST);
        }else if(industry.getLevel() == 3){
            //二级节点不会动
            redis.del(CHILD_INDUSTRY_LIST+":byId="+industry.getFatherId());
        }
    }

    /**
     * 调用刷新行业缓存的方法
     * @return
     */
    @PostMapping("refreshIndustry")
    public GraceJSONResult refreshIndustry(){

        //获取后一天日期
        String tomorrow = LocalDate.now().plusDays(1L) + " 03:00:00";
        LocalDateTime futureTime = LocalDateUtils.parseLocalDateTime(tomorrow,
                LocalDateUtils.DATETIME_PATTERN);
        //计算与现在时间的时间差
        Long publishTime = LocalDateUtils.getChronoUnitBetween(LocalDateTime.now(),
                                                                    futureTime,
                                                                    ChronoUnit.MILLIS);
        int delayTimes = publishTime.intValue();

        // 每天凌晨通过延迟队列更新一下缓存
        delayTimes = 10*1000;
        MessagePostProcessor messagePostProcessor = DelayIndustryConfig.setDelayTimes(delayTimes);

        //生产一条延迟消息
        rabbitTemplate.convertAndSend(DelayIndustryConfig.EXCHANGE_DELAY_REFRESH,
                DelayIndustryConfig.DELAY_REFRESH_INDUSTRY,
                "123456",
                messagePostProcessor);


        return GraceJSONResult.ok();
    }
}
